#--*--coding=utf-8--*--
#MaterialCodeGenerator3.py

import sys
import json
import sqlite3
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QComboBox, QLineEdit, QHBoxLayout, QMessageBox
from PySide6.QtCore import Qt
from PySide6.QtGui import QClipboard

import chardet

"""
        # 从JSON文件加载编码规则
        with open('rules.json', 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            self.encoding = result['encoding']
            
        with open('rules.json', 'r', encoding=self.encoding) as f:
            self.rules = json.load(f)

"""

# 加载规则load_rules_from_json
def load_rules_from_json(file_path):
    #with open(file_path, 'r') as file:
        #return json.load(file)
    
    # 从JSON文件加载编码规则
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)#(raw_data)
        encoding = result['encoding']    
    
    with open(file_path, 'r', encoding=encoding) as file:
        return json.load(file)
        
        
def load_rules_from_db(db_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    rules = {}
    
    # 读取第1组规则
    cursor.execute("SELECT name, code FROM part1")
    rules['part1'] = {name: code for name, code in cursor.fetchall()}
    
    # 读取第2组规则
    cursor.execute("SELECT name, code FROM part2")
    rules['part2'] = {name: code for name, code in cursor.fetchall()}
    
    # 读取第3组规则
    cursor.execute("SELECT name, code FROM part3")
    rules['part3'] = {name: code for name, code in cursor.fetchall()}
    
    conn.close()
    return rules

class ComboBoxWithSearch(QComboBox):
    def __init__(self, items, parent=None):
        super().__init__(parent)
        self.setEditable(True)
        self.setInsertPolicy(QComboBox.NoInsert)
        self.addItems(items)
        self.lineEdit().textChanged.connect(self.filter_items)
    
    def filter_items(self, text):
        self.clear()
        for item in self.all_items:
            if text.lower() in item.lower():
                self.addItem(item)

class DynamicComboBox(QWidget):
    def __init__(self, items, index, main_widget, rules):
        super().__init__()
        self.index = index
        self.main_widget = main_widget
        self.rules = rules
        self.layout = QHBoxLayout()
        
        self.combo = ComboBoxWithSearch(items)
        self.combo.all_items = items
        self.combo.currentTextChanged.connect(self.update_label)
        
        self.add_button = QPushButton("+")
        self.add_button.clicked.connect(self.add_group)
        
        self.remove_button = QPushButton("-")
        self.remove_button.clicked.connect(self.remove_group)
        
        self.layout.addWidget(self.combo)
        self.layout.addWidget(self.add_button)
        self.layout.addWidget(self.remove_button)
        self.setLayout(self.layout)
    
    def update_label(self, text):
        self.main_widget.update_code()
    
    def add_group(self):
        self.main_widget.add_group()
    
    def remove_group(self):
        self.main_widget.remove_group(self.index)

class MaterialCodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("物料编码生成器")
        self.setGeometry(100, 100, 400, 300)
        
        self.layout = QVBoxLayout()
        self.groups = []
        self.code_label = QLabel("编码:")
        self.copy_button = QPushButton("复制")
        self.copy_button.clicked.connect(self.copy_code)
        
        self.layout.addWidget(self.code_label)
        self.layout.addWidget(self.copy_button)
        
        self.add_group()
        
        self.setLayout(self.layout)
    
    def add_group(self):
        if len(self.groups) < 3:
            index = len(self.groups)
            if index == 0:
                items = list(rules['part1'].keys())
            elif index == 1:
                items = list(rules['part2'].keys())
            else:
                items = list(rules['part3'].keys())
            
            group = DynamicComboBox(items, index, self, self.rules)
            self.groups.append(group)
            self.layout.insertWidget(len(self.groups), group)
    
    def remove_group(self, index):
        if len(self.groups) > 1:
            widget = self.groups.pop(index)
            self.layout.removeWidget(widget)
            widget.deleteLater()
    
    def update_code(self):
        code_parts = []
        for i, group in enumerate(self.groups):
            combo = group.findChild(QComboBox)
            if i == 0:
                code_parts.append(self.rules['part1'][combo.currentText()])
            elif i == 1:
                code_parts.append(self.rules['part2'][combo.currentText()])
            else:
                code_parts.append(self.rules['part3'][combo.currentText()])
        
        code = '.'.join(code_parts)
        self.code_label.setText(f"编码: {code}")
    
    def copy_code(self):
        code = self.code_label.text().split(': ')[1]
        clipboard = QApplication.clipboard()
        clipboard.setText(code)
        QMessageBox.information(self, "提示", "编码已复制到剪贴板！")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 加载规则
    rules = load_rules_from_json('rules.json')
    #rules.update(load_rules_from_db('material.db'))
    
    window = MaterialCodeGenerator()
    window.show()
    
    sys.exit(app.exec())